package com.xl.studentpass.service.impl;

import com.xl.studentpass.service.LikeAndFavoriteService;
import com.xl.studentpass.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

import static com.xl.studentpass.utils.TaskOrderStatus.FAVORITE;
import static com.xl.studentpass.utils.TaskOrderStatus.LIKE;

/**
 * @author: xl
 * @createTime: 2023/6/10 20:31:08
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description:
 */
@Service
@Slf4j
public class LikeAndFavoriteServiceImpl implements LikeAndFavoriteService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * @param communityId 帖子id
     * @param userId      用户id
     * @param categoryId  <li>0 喜欢</li><li>1 收藏</li>
     */
    @Override
    public R giveLikeAndFavorite(Integer communityId, Integer userId, Integer categoryId) {

        log.error(categoryId + "===============");

        try {
            if (categoryId.equals(0)) {
                saveToRedis(communityId, userId, LIKE.getStatusName());
            } else {
                saveToRedis(communityId, userId, FAVORITE.getStatusName());
            }
            return R.ok();
        } catch (RuntimeException e) {
            log.info("点赞信息错误");
            return R.error();
        }
    }

    private void saveToRedis(Integer communityId, Integer userId, String type) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        String community = "community:" + communityId;
        Set<Object> hashKeys = opsForHash.keys(community);
        for (Object x : hashKeys) {
            String keys = (String) x;
            if (keys.contains(String.valueOf(userId)) && keys.contains(type)) {
                opsForHash.increment(community, type + ":" + userId, -1L);
                int count = Integer.parseInt(
                        (String) Objects.requireNonNull(opsForHash.get(community, type + ":" + userId))
                );

                if (!ObjectUtils.isEmpty(count) && count <= 0) {
                    opsForHash.delete(community, type + ":" + userId);
                    opsForHash.delete("userId:" + userId, type + ":" + communityId);
                }
                return;
            }
        }
        opsForHash.increment(community, type + ":" + userId, 1L);
        opsForHash.put("userId:" + userId, type + ":" + communityId, "0");

    }
}
